import { defineComponent, ref, reactive, shallowRef } from 'vue'
import { useStore } from 'vuex'
import useAMap from '~/hooks/useAMap'
import manhole1 from '~/assets/manhole1.png'
import manhole2 from '~/assets/manhole2.png'
import manhole3 from '~/assets/manhole3.png'
import useVuexGetters from '~/hooks/useVuexGetters'

export default defineComponent({
  name: 'ManholeRunmap',
  props: ['id', 'getMapZoom'],
  emits: ['handleMonitorInfo'],
  setup(props, { expose, emit }) {
    const store = useStore()
    const mapDomRef = ref()
    const runmapState = useVuexGetters('runmap', ['runStatus'])
    const state = reactive<any>({
      loca: null,
      monitor1: null,
      monitorMakers1: [],
      monitor2: null,
      monitorMakers2: [],
      monitor3: null,
      monitorMakers3: [],
      detail: null
    })
    const userState = useVuexGetters('user', ['userAddressInfo'])
    const [mapRef, aMapRef] = useAMap(
      props.id,
      {
        zoom: 12,
        mapStyle: 'amap://styles/whitesmoke',
        center: [userState.userAddressInfo.value.lon, userState.userAddressInfo.value.lat]
      },
      initAMap
    )
    //  请求点位
    const index = async () => {
      try {
        const { data } = await store.dispatch('manholes/ManholeMapGetManholePointAllGet')
        for (let i = 0; i < data.length; i++) {
          const item = data[i]
          if (item.state === '1') {
            //  正常
            state.monitorMakers1.push(item)
          }
          if (item.state === '2') {
            //  故障
            state.monitorMakers2.push(item)
          }
          if (item.state === '3') {
            //  离线
            state.monitorMakers3.push(item)
          }
        }
        FeatureCollectionMaker(state.monitorMakers1, 1)
        FeatureCollectionMaker(state.monitorMakers2, 2)
        FeatureCollectionMaker(state.monitorMakers3, 3)
      } catch (error) {}
    }
    //  FeatureCollection
    const FeatureCollectionMaker = (array: any, status: number) => {
      const arr: any[] = []
      for (let i = 0; i < array.length; i++) {
        const item = array[i]
        arr.push({
          type: 'Feature',
          properties: {
            name: item.name,
            state: item.state,
            detail: item
          },
          geometry: {
            type: 'Point',
            coordinates: [Number(item.lon), Number(item.lat)]
          }
        })
      }
      const geo = new window.Loca.GeoJSONSource({
        data: {
          type: 'FeatureCollection',
          features: arr
        }
      })
      state[`monitor${status}`].setSource(geo)
      state[`monitor${status}`].setStyle({
        text: {
          content: (feat: any) => feat.properties.name
        },
        icon: stateConvert(status),
        iconSize: [20, 20]
      })
      state.loca.add(state[`monitor${status}`])
    }
    //  状态转换
    const stateConvert = (value: number) => {
      let icon
      if (value === 1) {
        icon = manhole1
      } else if (value === 2) {
        icon = manhole2
      } else {
        icon = manhole3
      }
      return icon
    }
    //  标点
    const marker = shallowRef()
    const markerLayer = (row: any) => {
      if (marker.value) {
        mapRef.value.remove(marker.value)
      }
      const content = `<div style='position: relative;transform: translate(-50%, -170%);'>
        <div style='white-space: nowrap;color: red;font-size: 14px;'>${row.content}</div>
        <div style='position: absolute;left: 50%;transform: translate(-50%, 0);'>
          <img src='${stateConvert(runmapState.runStatus.value)}' width='30px' height='30px' />
        </div>
      </div>`
      marker.value = new aMapRef.value.Marker({
        position: row.markers,
        content,
        offset: [0, 0]
      })
      mapRef.value.add(marker.value)
      mapRef.value.setFitView()
    }
    function initAMap() {
      state.loca = new window.Loca.Container({
        map: mapRef.value
      })
      //  井盖-正常
      state.monitor1 = new window.Loca.IconLayer({
        zIndex: 300,
        opacity: 1,
        visible: true
      })
      //  井盖-故障
      state.monitor2 = new window.Loca.IconLayer({
        zIndex: 300,
        opacity: 1,
        visible: true
      })
      //  井盖-离线
      state.monitor3 = new window.Loca.IconLayer({
        zIndex: 300,
        opacity: 1,
        visible: true
      })
      index()

      //  地图缩放
      mapRef.value.on('zoomend', () => {
        props.getMapZoom?.()
      })
      //  地图点击
      mapRef.value.on('click', (e: any) => {
        for (let i = 0; i < 3; i++) {
          const feat = state[`monitor${i + 1}`].queryFeature(e.pixel.toArray())
          if (feat) {
            state.detail = feat.properties.detail
            emit('handleMonitorInfo', state.detail.id)
          }
        }
      })
    }
    expose({
      map: mapRef,
      aMap: aMapRef,
      markerLayer
    })
    return () => {
      return <section id={props.id} ref={mapDomRef}></section>
    }
  }
})
